import { NextRequest, NextResponse } from 'next/server'
import { readFile, stat } from 'fs/promises'
import { join } from 'path'
import { lookup } from 'mime-types'

export async function GET(
  request: NextRequest,
  { params }: { params: { toolId: string; path: string[] } }
) {
  try {
    const { toolId, path } = params
    
    // 构建文件路径
    const fileName = path?.join('/') || 'index.html'
    const filePath = join(process.cwd(), 'public', 'deployed-tools', toolId, fileName)
    
    console.log(`访问工具文件: ${filePath}`)
    
    // 检查文件是否存在
    try {
      await stat(filePath)
    } catch (error) {
      console.log(`文件不存在: ${filePath}`)
      return new NextResponse('File not found', { status: 404 })
    }
    
    // 读取文件内容
    const fileContent = await readFile(filePath)
    
    // 确定MIME类型
    const mimeType = lookup(fileName) || 'application/octet-stream'
    
    console.log(`返回文件: ${fileName}, MIME类型: ${mimeType}`)
    
    // 返回文件内容
    return new NextResponse(fileContent, {
      status: 200,
      headers: {
        'Content-Type': mimeType,
        'Cache-Control': 'public, max-age=3600', // 缓存1小时
      },
    })
    
  } catch (error) {
    console.error('访问工具文件失败:', error)
    return new NextResponse('Internal Server Error', { status: 500 })
  }
}
